package com.lj.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lj.eduservice.entity.Subject;
import com.lj.eduservice.entity.node.SubjectNode;
import com.lj.eduservice.mapper.SubjectMapper;
import com.lj.eduservice.service.SubjectService;
import com.lj.utils.exception.APIException;
import com.lj.utils.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author luojing
 * @since 2021-04-28
 */
@Service
@Slf4j
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public void saveSubject(MultipartFile file){
        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, new SubjectExcelListener(this)).sheet().doRead();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }


    private class SubjectExcelListener extends AnalysisEventListener<Map<Integer, String>> {

        private SubjectService subjectService;
        private Map<String, String> subjectMap = new HashMap<>();

        private SubjectExcelListener(SubjectService subjectService) {
            this.subjectService = subjectService;
        }

        /**
         * Excel
         * 1.可以只写一列 表示这个科目父科目是根
         * 2.可以写任意列 从根开始，如果某一列没有则创建
         * <p>
         * 3.标题可以重复而且要根据Excel的结构来
         *
         * @param subjects
         * @param analysisContext
         */
        @Override
        public void invoke(Map<Integer, String> subjects, AnalysisContext analysisContext) {

            Collection<String> titles = subjects.values();
            String parentId = "0";
            //循环遍历这一行每一个科目标题，没有就创建
            for (String title : titles) {
                String subjectId = getSubjectId(title,parentId);
                //没有就创建
                if (subjectId == null){
                    Subject subject = new Subject();
                    subject.setTitle(title);
                    subject.setParentId(parentId);
                    boolean save = subjectService.save(subject);
                    if (save){
                        subjectId = getSubjectId(subject.getTitle(),subject.getParentId());
                    }
                }
                //有把他的id给parentId
                parentId = subjectId;
            }
        }

        /**
         * 根据科目名称和他的父科目id查询数据库中是否有当前的科目，如果有返回他的id,没有null
         * subjectMap 是为了防止多次重复查数据库做的缓存
         *
         * @param subjectTitle
         * @return
         */
        private String getSubjectId(String subjectTitle,String parentId) {
            //查看缓存里是否有
            String id = subjectMap.get(subjectTitle+"_"+parentId);
            if (id == null) {
                //查看数据库里是否有
                Subject subject = subjectService.getOne(new QueryWrapper<Subject>()
                        .eq("title", subjectTitle)
                        .eq("parent_id",parentId));
                if (subject != null) {
                    //有就放缓存并返回id
                    subjectMap.put(subject.getTitle()+"_"+parentId, subject.getId());
                    return subject.getId();
                }
                return null;
            }
            return id;
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        }
    }

    //获取所有的课程分类列表以树的数据结构返回（递归）
    @Override
    public List<SubjectNode> getListTree(){
        SubjectNode rootNode = new SubjectNode("0","");
        getNodeChildren(rootNode);
        return rootNode.getChildrens();
    }

    private void getNodeChildren(SubjectNode subjectNode){
        List<Subject> children = this.list(new QueryWrapper<Subject>().eq("parent_id", subjectNode.getId()));
        for (Subject child : children) {
            SubjectNode childNode = new SubjectNode(child.getId(), child.getTitle());
            getNodeChildren(childNode);
            subjectNode.addChildren(childNode);
        }
    }

}
